//
//  NetCommand.m
//  LegoClient
//
//  Created by Balazs Faludi on 02.01.10.
//  Copyright 2010 Universität Basel. All rights reserved.
//

#import "NetCommand.h"
#import "NetMessage.h"

@interface NetCommand () 

@property (nonatomic, retain) NSString *head;
@property (nonatomic, retain) NSString *body;

@end


@implementation NetCommand

@synthesize head = _head;
@synthesize body = _body;

#pragma mark -
#pragma mark Constructors & Destructor

- (void)updateArgs {
	if(_args) [_args release];
	_args = [[self.body componentsSeparatedByString:@" "] retain];
	_argc = [_args count];
}

- (id)initWithHead:(NSString *)newHead body:(NSString *)newBody 
{
	self = [super init];
	if (self != nil) {
		self.head = newHead;
		self.body = newBody;
		[self updateArgs];
	}
	return self;
}

- (id)initWithBytes:(const uint8_t *)bytes length:(NSUInteger)length 
{
	self = [super init];
	if (self != nil) {
		NSString *string = [[NSString alloc] initWithBytes:bytes length:length encoding:kNetMessageEncoding];
		NSString *head = [string substringToIndex:kNetCommandHeadLength];
		NSString *body = [string substringFromIndex:kNetCommandHeadLength + [kNetCommandDelimiter length]];
		self.head = head;
		self.body = body;
		[self updateArgs];
	}
	return self;
}

- (id)initWithMessage:(NetMessage *)message 
{
	self = [super init];
	if (self != nil) {
		NSString *string = [message stringValue];
		if([string length] < 4) return nil;
		NSString *head = [string substringToIndex:kNetCommandHeadLength];
		NSString *body = @"";
		if([string length] >= 5)
			body = [string substringFromIndex:kNetCommandHeadLength + [kNetCommandDelimiter length]];
		self.head = head;
		self.body = body;
		[self updateArgs];
	}
	return self;
}

- (void) dealloc
{
	self.head = nil;
	self.body = nil;
	if(_args) [_args release];
	[super dealloc];
}

#pragma mark -
#pragma mark Getters & Setters

- (NSString *)stringValue {
	return [NSString stringWithFormat:@"%@%@%@", self.head, kNetCommandDelimiter, self.body];
}

- (NetMessage *)message {
	return [[[NetMessage alloc] initWithString:[self stringValue]] autorelease];
}

- (const uint8_t *)bytes {
	return [[[self stringValue] dataUsingEncoding:kNetMessageEncoding] bytes];
}

- (NSUInteger)length {
	return [[[self stringValue] dataUsingEncoding:kNetMessageEncoding] length];
}

- (NSString *)getArgumentAtIndex:(int)index {
	if([_args count] <= index) return nil;
	return [_args objectAtIndex:index];
}

- (NSArray *)getArguments {
	return _args;
}

- (int)count {
	return _argc;
}

- (NSString *)head {
	return _head;
}

- (NSString *)body {
	return _body;
}

@end
